// import { createCircular } from './utils.js'
// 获取dom
const can = document.getElementById('canvas')
const ctx = can.getContext('2d')

const mouse = {
  x: 0,
  y: 0
}

/**
 * 创建圆
 * @param {ctx} ctx 实例
 * @param {number} x x轴
 * @param {number} y y轴
 * @param {number} r 半径
 */
 function createCircular(ctx, x, y, r, color) {
  // arc 参数文档 https://www.w3school.com.cn/tags/canvas_arc.asp
  ctx.arc(x, y, r, 0, 2 * Math.PI, false)
  ctx.fillStyle = color
  ctx.fill()
}

/**
 * 初始化
 * @param {number} createNum 生成球的数量
 * @param {number} rMax 规定鼠标悬浮时球半径的最大值
 * @param {number} mouseScope 规定鼠标悬浮时 多少半径内会变大
 * @param {number} width 宽度
 * @param {number} height 高度
 */
function init(createNum, rMax = 50,mouseScope = 50, width = document.body.clientWidth, height = document.body.clientHeight) {
  const w = width
  const h = height

  can.width = w
  can.height = h

  can.addEventListener("mousemove", (e) => {
    mouse.x = e.x
    mouse.y = e.y
  })

  /**
   * 定义绘制
   * @param {number} x 
   * @param {number} y 
   * @param {number} r 半径
   * @param {number} sx x轴速度 
   * @param {number} sy y轴速度 每帧增加多少
   * @param {string} color
   */
  function Ball(x, y, r, sx, sy, color) {
    this.x = x
    this.y = y
    this.r = r
    this.oldR = r
    this.sx = sx
    this.sy = sy
    this.color = color

    // 绘制
    this.draw = () => {
      // 重新绘制路径 https://www.w3school.com.cn/tags/canvas_beginpath.asp
      ctx.beginPath()
      createCircular(ctx, this.x, this.y, this.r, this.color)
    }

    // 更新
    this.update = () => {
      // 改变参数 绘制的时候 使球动起来
      if (this.x + this.r >= w || this.x - this.r <= 0) this.sx = -this.sx
      if (this.y + this.r >= h || this.y - this.r <= 0) this.sy = -this.sy
      this.x += this.sx
      this.y += this.sy

      // 改变参数 绘制的时候 使球变大
      if ((mouse.x - this.x < mouseScope && mouse.x - this.x > -mouseScope) && (mouse.y - this.y < mouseScope && mouse.y - this.y > -mouseScope)) {
        this.r = this.r <= rMax ? this.r + 1 : this.r + 0
      } else {
        this.r = this.r > this.oldR ? this.r - 1 : this.r - 0 
      }

      // 调用绘制
      this.draw()
    }

  }

  // 定义颜色
  const colors = ['#FC8E62', '#D95597', '#A869F0', '#5580D9', '#55FAE7', '#4BC2C4', '#5ED455', '#E8D964', '#FFAA61', '#F25084']
  // 所有球所在位置
  const ballArray = []

  for (let i in new Array(createNum).fill('')) {
    let x = Math.random() * w
    let y = Math.random() * h
    let r = Math.random() * 2 + 2
    let sx = Math.random() * 2
    let sy = Math.random() * 2
    let color = colors[Math.floor(Math.random() * 10)]

    ballArray.push(new Ball(x, y, r, sx, sy, color))
  }
  // 生成球
  function animate() {
    requestAnimationFrame(animate)
    // 清除像素 https://www.w3school.com.cn/tags/canvas_clearrect.asp
    ctx.clearRect(0, 0, w, h)
    ballArray.forEach(ball => {
      ball.update()
    })

  }

  animate()
}